// ignore_for_file: file_names

import 'dart:async';
import 'dart:collection';
import 'package:get/get.dart';
import 'package:verse_systems/net/http_dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/utils/check_regexp.dart';
import 'package:verse_systems/utils/toast_utils.dart';

class TimerCountDownWidget extends StatefulWidget {
  final String mobile;
  final Function onTimerFinish;

  const TimerCountDownWidget(this.mobile,
      {Key? key, required this.onTimerFinish})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => TimerCountDownWidgetState();
}

class TimerCountDownWidgetState extends State<TimerCountDownWidget> {
  Timer? _timer;
  int _countdownTime = 0;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (_countdownTime == 0) {
          setState(() {
            _countdownTime = 60;
          });
          //开始倒计时
          startCountdownTimer();
          _verificationCodeSend(widget.mobile, "login");
        }
      },
      child: Container(
        decoration: BoxDecoration(
            color: _countdownTime > 0
                ? Colors.transparent
                : Colours.app_main_background_color,
            borderRadius: BorderRadius.only(
                topRight: Radius.circular(8.w),
                bottomRight: Radius.circular(8.w))),
        height: 46.w,
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        alignment: Alignment.center,
        child: Text(
          _countdownTime > 0 ? '${"sent".tr}($_countdownTime)s' : "get_code".tr,
          style: TextStyle(
              fontSize: 15.sp,
              color: _countdownTime > 0
                  ? Colours.app_sendcode_color
                  : Colours.app_main_color),
        ),
      ),
    );
  }

  void startCountdownTimer() {
    _timer = Timer.periodic(
        const Duration(seconds: 1),
        (Timer timer) => {
              if (mounted)
                {
                  setState(() {
                    if (_countdownTime < 1) {
                      widget.onTimerFinish();
                      _timer?.cancel();
                    } else {
                      _countdownTime = _countdownTime - 1;
                    }
                  })
                }
            });
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer?.cancel();
    }
  }

  ///获取验证码
  _verificationCodeSend(String mobile, String event) async {
    if (!CheckRegexp.isChinaPhoneLegal(mobile)) {
      showToast("phone_error".tr);
      if (_countdownTime > 0) {
        setState(() {
          _countdownTime = 0;
        });
      }

      return;
    }

    Map<String, dynamic> map = HashMap();
    map['phone'] = mobile;

    Request.postCallback(
      HttpUrls.getSmsCodeUrl,
      data: map,
      needToken: false,
      success: (res) async {
        showToast("send_success".tr);
        debugPrint('获取验证码res:${res.toString()}');
      },
      error: (err) {
        showToast(err.message);
        debugPrint('获取验证码err----- err:${err.toString()}');
      },
    );
  }
}
